/*
 * Copyright (C) 2022 HiHope Open Source Organization .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http:// www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 *
 * limitations under the License.
 */

#include <stdio.h>
#include <string.h>
#include "ohos_init.h"
#include "cmsis_os2.h"

#include "wifi_connecter.h"
#define TEN 10
#define ONE_HUNDRED 100

#if CHIP_WS63
#define STACK_SIZE 10240
#define MAX_CONNECT_RETRY_TIMES 16
#define CONNECT_ATTEMPT_INTERVAL_MS 300
#else
#define ATTR.STACK_SIZE 10240
#endif

static void WifiConnectTask(int *arg)
{
    (void)arg;

    osDelay(TEN);

    // setup your AP params
    // 设置AP参数，包括SSID、预共享密钥、安全类型（PSK）、netID
    WifiDeviceConfig apConfig = {0};
    if (strcpy_s(apConfig.ssid, sizeof(apConfig.ssid), "r1")) {
        printf("OK");
    }

    if (strcpy_s(apConfig.preSharedKey, sizeof(apConfig.preSharedKey), "88888889")) {
        printf("OK");
    }

    apConfig.securityType = WIFI_SEC_TYPE_PSK;

#if CHIP_WS63
    int netId = -1;

    // demo启动时，系统的WiFi功能可能没有初始化完毕，需要等待不确定的时候。待优化。
    for (uint8_t i = 0; i < MAX_CONNECT_RETRY_TIMES; i++) {
        osDelay(CONNECT_ATTEMPT_INTERVAL_MS);
        netId = ConnectToHotspot(&apConfig);
        if (netId >= 0) {
            break;
        }
    }
#else
    int netId = ConnectToHotspot(&apConfig);
#endif
}

static void WifiConnectDemo(void)
{
    osThreadAttr_t attr;

    attr.name = "WifiConnectTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
#if CHIP_WS63
    attr.stack_size = STACK_SIZE;
#else
    attr.stack_size = ATTR.STACK_SIZE;
#endif
    attr.priority = osPriorityNormal;

    if (osThreadNew(WifiConnectTask, NULL, &attr) == NULL) {
        printf("[WifiConnectDemo] Failed to create WifiConnectTask!\n");
    }
}

SYS_RUN(WifiConnectDemo);
